const jwt = require('jsonwebtoken')
const { config } = require('../config/default')
const mysqlModel = require('../lib/group')
const ApiErrorNames = require('../error/ApiErrorNames')
const { nanoid } = require('nanoid')
const moment = require('moment')
const ali = require('../util/aliOSS_utils')

/*
 创建分组
 */
let createGroup=async (ctx, next)=>{
  const { body } = ctx.request
  try {
    //获得token
    const token=ctx.headers.authorization
    let payload
    if(token){
      payload=await jwt.verify(token.split(' ')[1],config.secret)
      const group = await mysqlModel.findGroup(body.name)
      if (group) {
        ctx.body = ApiErrorNames.getErrorInfo(ApiErrorNames.UNKNOWN_ERROR)
        return
      }
      const groupId = nanoid(12)
      let info =
        {
          ID: groupId,
          GROUP_NAME: body.name,
          ADDRESS: '',
          DESCRIPTION: body.description,
          STATUS: '1',
          CREATED_BY: payload.user_name,
          CREATED_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
          UPDATED_BY: payload.user_name,
          UPDATED_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
        }
      let groupInfo=
        {
          USER_ID: payload.user,
          GROUP_ID: groupId,
          STATUS: '1',
          AUTH: '1001',
          CREATED_BY: payload.user_name,
          CREATED_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
          UPDATED_BY: payload.user_name,
          UPDATED_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
        }
      await mysqlModel
        .createGroup(info,groupInfo)
        .then(() => {
          ctx.body = ApiErrorNames.getSuccessInfo(`创建分组 ${body.name} 成功!`)
          let client=ali.getClient()
          //创建文件夹
          ali.createFolder(client,`g-${body.name}`)
        })
        .catch(() => {
          ctx.body = ApiErrorNames.getErrorInfo(ApiErrorNames.UNKNOWN_ERROR)
        })
    }

  } catch (error) {
    ApiErrorNames.errorCatch(error, ctx)
  }
}
/*
邀请人进分组
 */
let inviteToGroup=async (ctx)=>{
  const { body } = ctx.request
  const {userId,groupId}=body
  let auth='1002'
  if(body.hasOwnProperty('AUTH')){
    auth=body['AUTH']
  }
  try{
    const token=ctx.headers.authorization
    let payload
    if(token){
      //鉴权 只有组创建者才能邀请人进分组
      payload=await jwt.verify(token.split(' ')[1],config.secret)
      let isLeader=await mysqlModel.isLeader(payload.user,groupId)
      if (isLeader){
        let groupInfo=
          {
            USER_ID: userId,
            GROUP_ID: groupId,
            STATUS: '1',
            AUTH:auth,
            CREATED_BY: payload.user_name,
            CREATED_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
            UPDATED_BY: payload.user_name,
            UPDATED_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
          }
        await mysqlModel.inviteToGroup(groupInfo)
          .catch((err => {
            ctx.body = ApiErrorNames.getErrorInfo(ApiErrorNames.DATA_IS_WRONG)
          }))
        ctx.body=ApiErrorNames.getSuccessInfo("邀请成功!")
      }
      else{
        ApiErrorNames.getErrorInfo(ApiErrorNames.USER_ACCOUNT_FORBIDDEN)
      }
    }
  }catch (e) {
    ApiErrorNames.errorCatch(e,ctx)
  }
}
/*
查看当前用户加入的分组
 */
let getGroupList=async (ctx)=>{
  const { body } = ctx.request
  const {id}=body
  try{
    const token=ctx.headers.authorization
    let payload
    if(token){
      payload=await jwt.verify(token.split(' ')[1],config.secret)
      let userId=payload.user
      if (id===userId){
        let result = await mysqlModel.getGroupList(id)
        ctx.body=ApiErrorNames.getSuccessInfo(result)
      }
      else{
        ApiErrorNames.getErrorInfo(ApiErrorNames.USER_ACCOUNT_FORBIDDEN)
      }
    }
  }catch (e) {
    ApiErrorNames.errorCatch(e,ctx)
  }
}
/*
查看分组所有的用户
 */
let getGroupUsers=async (ctx)=>{
  const { body } = ctx.request
  const {groupId}=body
  try{
    const token=ctx.headers.authorization
    if(token){
      let payload = await jwt.verify(token.split(' ')[1],config.secret)
      let result = await mysqlModel.getAllGroupUser(groupId)
      let isLeader = await mysqlModel.isLeader(payload.user,groupId)
      ctx.body=ApiErrorNames.getSuccessInfo({
        isLeader:isLeader,
        users:result
      })
    }
  }catch (e) {
    ApiErrorNames.errorCatch(e,ctx)
  }
}
/*
分配组权限
 */
let allocateGroupAuth=async (ctx)=>{
  const { body } = ctx.request
  const {userId,groupId,auth}=body
  try{
    let newAuth=auth==='1002'?'1003':'1002'
    const token=ctx.headers.authorization
    if(token){
      await jwt.verify(token.split(' ')[1],config.secret)
      let result = await mysqlModel.allocateGroupAuth(userId,groupId,newAuth)
      ctx.body=ApiErrorNames.getSuccessInfo('分配成功!')
    }
  }catch (e) {
    ApiErrorNames.errorCatch(e,ctx)
  }
}
/*
踢出用户
 */
let deleteUser =async (ctx)=>{
  const { body } = ctx.request
  const {userId,groupId}=body
  try{
    const token=ctx.headers.authorization
    if(token){
      let payload=await jwt.verify(token.split(' ')[1],config.secret)
      let result = await mysqlModel.deleteFromGroup(userId,groupId)
      ctx.body=ApiErrorNames.getSuccessInfo('操作成功!')
    }
  }catch (e) {
    ApiErrorNames.errorCatch(e,ctx)
  }
}
/*
更新组织
 */
let updateGroup =async (ctx)=>{
  const { body } = ctx.request
  const {groupId,name,des}=body
  try{
    const token=ctx.headers.authorization
    if(token){
      let payload=await jwt.verify(token.split(' ')[1],config.secret)
      let isLeader=await mysqlModel.isLeader(payload.user,groupId)
      let oldName=await mysqlModel.getNameById(groupId)
      if (isLeader){
        let client=ali.getClient()
        await ali.createFolder(client,`g-${name}`)
        await ali.deleteFile(client,`g-${oldName}/`)
        let result = await mysqlModel.updateGroup(groupId,name,des)
        ctx.body=ApiErrorNames.getSuccessInfo('操作成功!')
      }else {
        ctx.body=ApiErrorNames.getErrorInfo('error')
      }
    }
  }catch (e) {
    ApiErrorNames.errorCatch(e,ctx)
  }
}
/*
转交组织
 */
let transferGroup =async (ctx)=>{
  const { body } = ctx.request
  const {groupId,userId}=body
  try{
    const token=ctx.headers.authorization
    if(token){
      let payload=await jwt.verify(token.split(' ')[1],config.secret)
      let isLeader=await mysqlModel.isLeader(payload.user,groupId)
      if (isLeader){
        let isInGroup = await mysqlModel.isInGroup(userId,groupId)
        if(isInGroup){
          await mysqlModel.allocateGroupAuth(userId,groupId,'1001')
          await mysqlModel.allocateGroupAuth(payload.user,groupId,'1002')
        }else{
          let groupInfo=
            {
              USER_ID: userId,
              GROUP_ID: groupId,
              STATUS: '1',
              AUTH:'1001',
              CREATED_BY: payload.user_name,
              CREATED_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
              UPDATED_BY: payload.user_name,
              UPDATED_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
          await mysqlModel.inviteToGroup(groupInfo)
          await mysqlModel.allocateGroupAuth(payload.user,groupId,'1002')
        }
        ctx.body=ApiErrorNames.getSuccessInfo('操作成功!')
      }else {
        ctx.body=ApiErrorNames.getErrorInfo('error')
      }
    }
  }catch (e) {
    ApiErrorNames.errorCatch(e,ctx)
  }
}
/*
解散团队
 */
let dissolutionGroup =async (ctx)=>{
  const { body } = ctx.request
  const {groupId}=body
  try{
    const token=ctx.headers.authorization
    if(token){
      let payload=await jwt.verify(token.split(' ')[1],config.secret)
      let isLeader=await mysqlModel.isLeader(payload.user,groupId)
      let oldName=await mysqlModel.getNameById(groupId)
      if (isLeader){
        let client=ali.getClient()
        await ali.deleteFile(client,`g-${oldName}/`)
        let result = await mysqlModel.dissolutionGroup(groupId)
        ctx.body=ApiErrorNames.getSuccessInfo('解散成功!')
      }else {
        ctx.body=ApiErrorNames.getErrorInfo('error')
      }
    }
  }catch (e) {
    ApiErrorNames.errorCatch(e,ctx)
  }
}
/*
获取当前权限
 */
let getAuth =async (ctx)=>{
  const groupId=ctx.params.groupId
  try{
    const token=ctx.headers.authorization
    if(token){
      let payload=await jwt.verify(token.split(' ')[1],config.secret)
      let result = await mysqlModel.getAuth(groupId,payload.user)
      ctx.body=ApiErrorNames.getSuccessInfo({isReadOnly:result==='1003'})
    }
  }catch (e) {
    ctx.body=ApiErrorNames.getErrorInfo(e,ctx)
  }
}
module.exports = {
  createGroup,
  inviteToGroup,
  getGroupList,
  getGroupUsers,
  allocateGroupAuth,
  deleteUser,
  updateGroup,
  transferGroup,
  dissolutionGroup,
  getAuth
}
